package siddur.traktask.facade;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import siddur.traktask.chrome.model.HourData;
import siddur.traktask.chrome.model.ScreenShotData;
import siddur.traktask.entity.Memo;
import siddur.traktask.entity.ScreenShot;
import siddur.traktask.entity.TaskInfo;
import siddur.traktask.entity.TrakPeriod;
import siddur.traktask.framework.FileSystemUtil;
import siddur.traktask.repository.MemoRepository;
import siddur.traktask.repository.ScreenShotRepository;
import siddur.traktask.repository.TaskRepository;
import siddur.traktask.repository.TrakPeriodRepository;
import siddur.traktask.util.ImageUtil;

@Service
public class TrakFacade {
	private static final Logger log4j = Logger.getLogger(TrakFacade.class);
	
	@Autowired TaskRepository taskRep;
	@Autowired ScreenShotRepository ssRep;
	@Autowired MemoRepository memoRep;
	@Autowired TrakPeriodRepository tpRep;
	
	public void saveScreenShot(List<ScreenShotData> data){
		for (ScreenShotData ssd : data) {
			ScreenShot screenShot = new ScreenShot();
			TaskInfo t = taskRep.findOne(ssd.getTaskId());
			screenShot.setTask(t);
			screenShot.setCreatedAt(new Date(ssd.getCreatedAt()));
			ssRep.save(screenShot);
			try {
				saveImage(screenShot, ssd.getImageData());
			} catch (Exception e) {
				log4j.error(e.getMessage(), e);
			}
		}
	}
	
	public void saveHour(List<HourData> data){
		for (HourData hd : data) {
			Date start = new Date(hd.getStart());
			int seconds = (int) hd.getSeconds();
			Date end = new Date(hd.getStart() + hd.getSeconds() * 1000);
			TaskInfo t = taskRep.findOne(hd.getTaskId());
			List<TrakPeriod> tpInDBs = tpRep.findByStartAtAndTask(start, t);
			if(tpInDBs.isEmpty()){
				TrakPeriod tp = new TrakPeriod();
				tp.setStartAt(start);
				tp.setEndAt(end);
				tp.setSeconds(seconds);
				tp.setTask(t);
				tpRep.save(tp);
			}else{ // if the new data has later enddate, update the former record
				TrakPeriod tpInDB = tpInDBs.get(0);
				if(end.after(tpInDB.getEndAt())){
					tpInDB.setEndAt(end);
					tpInDB.setSeconds(seconds);
					tpRep.save(tpInDB);
				}
			}
		}
	}
	
	public void saveMemo(List<HourData> data){
		for (HourData hd : data) {
			Date start = new Date(hd.getStart());
			TaskInfo t = taskRep.findOne(hd.getTaskId());
			String comment = hd.getComment();
			Memo m = new Memo();
			m.setTask(t);
			m.setCreatedAt(start);
			m.setComment(comment);
			memoRep.save(m);
		}
	}
	
	
	private void saveImage(ScreenShot ss, String imgData) throws IOException{
		if(imgData.length() < 100){
			log4j.info("Image Data is empty:" + imgData);
			return;
		}
		String flag = "data:image/jpeg;base64,";
		int start = flag.length();
		imgData = imgData.substring(start);
		byte[] imageData = org.apache.commons.codec.binary.Base64.decodeBase64(imgData);
		File f = new File(FileSystemUtil.getImageDir(), ss.getImageURL());
		f.getParentFile().mkdirs();
		FileUtils.writeByteArrayToFile(f, imageData);
		ImageUtil.resize(f);
	}
}
